<script lang="ts" setup>
import { ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  Row,
  Select,
  SelectOption,
  Switch,
  Textarea,
} from 'ant-design-vue';

import RboWorkflowDesigner from '../../workflow-designer/index';
import PerformanceMonitor from './PerformanceMonitor.vue';
import RboRuleEngine from './RboRuleEngine.vue';

// Props
const props = defineProps<{
  capability?: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
}>();

// 抽屉相关
const [WorkflowDrawer, workflowDrawerApi] = useVbenDrawer({
  title: 'RBO工作流设计器',
  class: 'workflow-drawer',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

const [RuleEngineDrawer, ruleEngineDrawerApi] = useVbenDrawer({
  title: 'RBO规则引擎',
  class: 'rule-engine-drawer',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

const [PerformanceMonitorDrawer, performanceMonitorDrawerApi] = useVbenDrawer({
  title: '性能监控',
  class: 'performance-monitor-drawer',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

// 响应式数据
const formData = ref({
  executionMode: 'sync',
  timeout: 30,
  retryCount: 1,
  mappings: [
    {
      type: 'input',
      source: 'userId',
      target: 'user_id',
      transform: 'none',
    },
  ],
  executionCondition: '',
  errorStrategy: 'fail_fast',
  errorNotification: true,
  errorHandler: '',
  enableMonitoring: true,
  performanceThreshold: 1000,
  monitorInterval: 60,
  logLevel: 'info',
  logInput: true,
  logOutput: false,
  inputValidation: true,
  outputFilter: false,
  securityRules: '',
});

// 监听props变化
watch(
  () => props.capability,
  (newCapability) => {
    if (newCapability?.behaviorExecution) {
      formData.value = {
        ...formData.value,
        ...newCapability.behaviorExecution,
      };
    }
  },
  { immediate: true },
);

// 方法
const handleFormChange = () => {
  emit('update', { behaviorExecution: formData.value });
};

const addMapping = () => {
  formData.value.mappings.push({
    type: 'input',
    source: '',
    target: '',
    transform: 'none',
  });
  handleFormChange();
};

const removeMapping = (index: number) => {
  formData.value.mappings.splice(index, 1);
  handleFormChange();
};

// 高级工具模态框状态
const workflowDesignerVisible = ref(false);
const ruleEngineVisible = ref(false);
const performanceMonitorVisible = ref(false);

// 高级工具方法
const openWorkflowDesigner = () => {
  console.log('打开工作流设计器');
  workflowDrawerApi.open();
};

const openRuleEngine = () => {
  console.log('打开规则引擎');
  ruleEngineDrawerApi.open();
};

const openPerformanceMonitor = () => {
  console.log('打开性能监控');
  performanceMonitorDrawerApi.open();
};
</script>

<template>
  <div class="capability-behavior-execution">
    <Form layout="vertical" :model="formData">
      <div class="behavior-execution-section">
        <h4>行为执行配置</h4>
        <p class="section-desc">配置能力的行为执行策略和监控</p>

        <!-- 执行策略 -->
        <div class="config-group">
          <h5>执行策略</h5>
          <Row :gutter="24">
            <Col :span="8">
              <FormItem label="执行模式" name="executionMode">
                <Select
                  v-model:value="formData.executionMode"
                  placeholder="请选择执行模式"
                  @change="handleFormChange"
                >
                  <SelectOption value="sync">同步执行</SelectOption>
                  <SelectOption value="async">异步执行</SelectOption>
                  <SelectOption value="batch">批量执行</SelectOption>
                  <SelectOption value="scheduled">定时执行</SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="超时时间(秒)" name="timeout">
                <InputNumber
                  v-model:value="formData.timeout"
                  :min="1"
                  :max="3600"
                  style="width: 100%"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="重试次数" name="retryCount">
                <InputNumber
                  v-model:value="formData.retryCount"
                  :min="0"
                  :max="10"
                  style="width: 100%"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 输入输出映射 -->
        <div class="config-group">
          <h5>输入输出映射</h5>
          <div class="mapping-list">
            <div
              v-for="(mapping, index) in formData.mappings"
              :key="index"
              class="mapping-item"
            >
              <Row :gutter="16">
                <Col :span="4">
                  <Select
                    v-model:value="mapping.type"
                    placeholder="类型"
                    @change="handleFormChange"
                  >
                    <SelectOption value="input">输入</SelectOption>
                    <SelectOption value="output">输出</SelectOption>
                  </Select>
                </Col>
                <Col :span="6">
                  <Input
                    v-model:value="mapping.source"
                    placeholder="源字段"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="6">
                  <Input
                    v-model:value="mapping.target"
                    placeholder="目标字段"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="4">
                  <Select
                    v-model:value="mapping.transform"
                    placeholder="转换规则"
                    @change="handleFormChange"
                  >
                    <SelectOption value="none">无</SelectOption>
                    <SelectOption value="string">字符串</SelectOption>
                    <SelectOption value="number">数字</SelectOption>
                    <SelectOption value="boolean">布尔值</SelectOption>
                    <SelectOption value="date">日期</SelectOption>
                  </Select>
                </Col>
                <Col :span="4">
                  <Button type="text" danger @click="removeMapping(index)">
                    删除
                  </Button>
                </Col>
              </Row>
            </div>
          </div>
          <Button
            type="dashed"
            @click="addMapping"
            style="width: 100%; margin-top: 16px"
          >
            <IconifyIcon icon="ant-design:plus-outlined" />
            添加映射
          </Button>
        </div>

        <!-- 执行条件 -->
        <div class="config-group">
          <h5>执行条件</h5>
          <FormItem label="条件表达式" name="executionCondition">
            <Textarea
              v-model:value="formData.executionCondition"
              placeholder="请输入执行条件表达式，例如：resource.status === 'idle' && user.hasPermission('execute')"
              :rows="4"
              @change="handleFormChange"
            />
          </FormItem>
          <div class="condition-help">
            <p>支持JavaScript表达式，可以使用以下变量：</p>
            <ul>
              <li><code>resource</code> - 当前资源对象</li>
              <li><code>user</code> - 当前用户对象</li>
              <li><code>context</code> - 执行上下文</li>
              <li><code>params</code> - 执行参数</li>
            </ul>
          </div>
        </div>

        <!-- 错误处理 -->
        <div class="config-group">
          <h5>错误处理</h5>
          <Row :gutter="24">
            <Col :span="12">
              <FormItem label="错误策略" name="errorStrategy">
                <Select
                  v-model:value="formData.errorStrategy"
                  placeholder="请选择错误处理策略"
                  @change="handleFormChange"
                >
                  <SelectOption value="fail_fast">快速失败</SelectOption>
                  <SelectOption value="continue">继续执行</SelectOption>
                  <SelectOption value="retry">重试</SelectOption>
                  <SelectOption value="compensate">补偿</SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="错误通知" name="errorNotification">
                <Switch
                  v-model:checked="formData.errorNotification"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
          <FormItem label="错误处理脚本" name="errorHandler">
            <Textarea
              v-model:value="formData.errorHandler"
              placeholder="请输入错误处理脚本"
              :rows="3"
              @change="handleFormChange"
            />
          </FormItem>
        </div>

        <!-- 性能监控 -->
        <div class="config-group">
          <h5>性能监控</h5>
          <Row :gutter="24">
            <Col :span="8">
              <FormItem label="启用监控" name="enableMonitoring">
                <Switch
                  v-model:checked="formData.enableMonitoring"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="性能阈值(ms)" name="performanceThreshold">
                <InputNumber
                  v-model:value="formData.performanceThreshold"
                  :min="100"
                  :max="10000"
                  style="width: 100%"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="监控间隔(秒)" name="monitorInterval">
                <InputNumber
                  v-model:value="formData.monitorInterval"
                  :min="1"
                  :max="300"
                  style="width: 100%"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 日志配置 -->
        <div class="config-group">
          <h5>日志配置</h5>
          <Row :gutter="24">
            <Col :span="8">
              <FormItem label="日志级别" name="logLevel">
                <Select
                  v-model:value="formData.logLevel"
                  placeholder="请选择日志级别"
                  @change="handleFormChange"
                >
                  <SelectOption value="debug">调试</SelectOption>
                  <SelectOption value="info">信息</SelectOption>
                  <SelectOption value="warn">警告</SelectOption>
                  <SelectOption value="error">错误</SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="记录输入" name="logInput">
                <Switch
                  v-model:checked="formData.logInput"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="记录输出" name="logOutput">
                <Switch
                  v-model:checked="formData.logOutput"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 高级工具 -->
        <div class="config-group">
          <h5>高级工具</h5>
          <Row :gutter="24">
            <Col :span="8">
              <Button type="primary" @click="openWorkflowDesigner">
                <IconifyIcon icon="ant-design:deployment-unit-outlined" />
                工作流设计器
              </Button>
            </Col>
            <Col :span="8">
              <Button type="primary" @click="openRuleEngine">
                <IconifyIcon icon="ant-design:setting-outlined" />
                规则引擎
              </Button>
            </Col>
            <Col :span="8">
              <Button type="primary" @click="openPerformanceMonitor">
                <IconifyIcon icon="ant-design:dashboard-outlined" />
                性能监控
              </Button>
            </Col>
          </Row>
        </div>

        <!-- 安全配置 -->
        <div class="config-group">
          <h5>安全配置</h5>
          <Row :gutter="24">
            <Col :span="12">
              <FormItem label="输入验证" name="inputValidation">
                <Switch
                  v-model:checked="formData.inputValidation"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="输出过滤" name="outputFilter">
                <Switch
                  v-model:checked="formData.outputFilter"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
          <FormItem label="安全规则" name="securityRules">
            <Textarea
              v-model:value="formData.securityRules"
              placeholder="请输入安全规则配置"
              :rows="3"
              @change="handleFormChange"
            />
          </FormItem>
        </div>
      </div>
    </Form>

    <!-- 工作流设计器抽屉 -->
    <WorkflowDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <RboWorkflowDesigner />
      </div>
    </WorkflowDrawer>

    <!-- 规则引擎抽屉 -->
    <RuleEngineDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <RboRuleEngine />
      </div>
    </RuleEngineDrawer>

    <!-- 性能监控抽屉 -->
    <PerformanceMonitorDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <PerformanceMonitor />
      </div>
    </PerformanceMonitorDrawer>
  </div>
</template>

<style lang="less">
.workflow-drawer,
.rule-engine-drawer,
.performance-monitor-drawer {
  width: 90% !important;
}
</style>

<style lang="less" scoped>
.capability-behavior-execution {
  padding: 24px;

  .behavior-execution-section {
    h4 {
      margin-bottom: 8px;
      color: #333;
      font-weight: 600;
    }

    .section-desc {
      margin-bottom: 24px;
      color: #666;
      font-size: 14px;
    }

    .config-group {
      margin-bottom: 32px;
      padding: 20px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fafafa;

      h5 {
        margin-bottom: 16px;
        color: #333;
        font-weight: 600;
        font-size: 16px;
      }

      .condition-help {
        margin-top: 12px;
        padding: 12px;
        background: #f5f5f5;
        border-radius: 4px;

        p {
          margin-bottom: 8px;
          color: #666;
          font-size: 12px;
        }

        ul {
          margin: 0;
          padding-left: 16px;

          li {
            margin-bottom: 4px;
            color: #666;
            font-size: 12px;

            code {
              background: #e6f7ff;
              padding: 2px 4px;
              border-radius: 2px;
              color: #1890ff;
            }
          }
        }
      }

      .mapping-list {
        .mapping-item {
          margin-bottom: 16px;
          padding: 16px;
          border: 1px solid #e8e8e8;
          border-radius: 6px;
          background: white;
        }
      }
    }
  }
}
</style>
